from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,BadData
from django.conf import settings

def generate_access_token_openid(openid):
    """序列化openid:将openid明文转密文"""

    # 创建序列化器对象:code过期时间时600秒,所以openid过期时间也是600秒
    s = Serializer(settings.SECRET_KEY,600)

    # 准备要序列化的数据 openid:封装在字典中
    data = {"openid":openid}

    # 序列化: 得到的结果时bytes 类型
    token = s.dumps(data)

    # 返回openid密文
    return token.decode()


def check__access_token_openid(access_token_openid):
    """反序列化openid: 将openid密文转明文"""

    # 创建序列化器对象:code过期时间时600秒,
    s = Serializer(settings.SECRET_KEY, 600)

    # 反序列化 data = {"openid":openid}
    # data = s.loads(access_token_openid)
    try:
        data = s.loads(access_token_openid)
    except BadData:
        return None
    else:
        # 返回反序列化后的openid
        return data.get("openid")


